package org.TCC_NOVO.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Image;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Margins;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Viewport;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarTextItem;
import com.gwtext.client.widgets.layout.AccordionLayout;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;
import com.gwtext.client.widgets.layout.FitLayout;
import com.gwtext.client.widgets.tree.AsyncTreeNode;
import com.gwtext.client.widgets.tree.TreeNode;
import com.gwtext.client.widgets.tree.TreePanel;
import com.gwtext.client.widgets.tree.XMLTreeLoader;
import com.gwtext.client.widgets.tree.event.TreePanelListenerAdapter;
import java.util.Date;

import org.TCC_NOVO.client.visual.DisponibilizarMaterialPanel;
import org.TCC_NOVO.client.visual.LoginForm;
import org.TCC_NOVO.client.visual.ProjetosPanel;
import org.TCC_NOVO.client.visual.RevisarTarefasPanel;
import org.TCC_NOVO.client.visual.AssumirTarefasPanel;
import org.TCC_NOVO.client.visual.BaixarArquivosProjetosPanel;
import org.TCC_NOVO.client.visual.DisponibilizarOAPanel;
import org.TCC_NOVO.client.visual.GerarSCORMPanel;
import org.TCC_NOVO.client.visual.SobreForm;
import org.TCC_NOVO.client.visual.UsuariosPanel;
import org.TCC_NOVO.client.visual.ValidarUnidadePanel;
import org.TCC_NOVO.client.visual.VerificarRevisoesPanel;

public class MainEntryPoint implements EntryPoint {

    private static final String odbc = "jdbc:firebirdsql:localhost/3050:E:/Pessoal/FURB/TCC_II/Banco_Dados/TCC.fdb";
    //private static final String odbc = "jdbc:firebirdsql:localhost/3050:C:/zeoa/TCC.fdb";

    private Panel loginPanel = new Panel();
    private TreePanel treePanelCad;
    private TreePanel treePanelsobre;
    private final GWTServiceAsync controller;
    TabPanel centerPanel;
    Panel westPanel;
    Panel panel;
    Panel borderPanel;
    BorderLayout borderLayout;
    Toolbar toolbar;

    Button btnLogoff;
    LoginForm loginForm;
    String sID_Usuario = "";
    String sNome = "";
    String sPapel = "";
    int iTamOriPanel = 0;

    public MainEntryPoint() {
        controller = GWTService.Util.getInstance();
        ServiceDefTarget endpoint = ( ServiceDefTarget )controller;
        String moduleRelativeURL = GWT.getModuleBaseURL()+"gwtservice";
        endpoint.setServiceEntryPoint( moduleRelativeURL );
    }

    private class callbackLogin implements AsyncCallback {
        @Override
	public void onFailure(Throwable e) {
            MessageBox.alert("Erro ao carregar dados... ", e.getMessage());
	}
        @Override
	public void onSuccess(Object result) {
            if(!result.equals("")) {
                sID_Usuario = result.toString().substring(0, result.toString().indexOf(","));
                sNome = result.toString().split(",")[1];
                sPapel = result.toString().split(",")[2];

                //fecha a tela de login
                loginForm.hide();

                //cria a tela principal
                panel = new Panel();
                panel.setBorder(false);
                panel.setPaddings(10);
                panel.setLayout(new FitLayout());

                borderPanel = new Panel();
                BorderLayout borderLayout = new BorderLayout();
                borderPanel.setLayout(borderLayout);

                Panel northPanel = new Panel();
                northPanel.setHeight(32);
                northPanel.setTitle("<center>Sistema Gerenciador de Objetos de Aprendizagem</center>");
                //northPanel.addButton(btnLogoff);
                borderPanel.add(northPanel, new BorderLayoutData(RegionPosition.NORTH));

                toolbar = new Toolbar();
                toolbar.setHeight(22);

                ToolbarTextItem textUsua = new ToolbarTextItem("Usuário: "+sNome);
                toolbar.addItem(textUsua);
                toolbar.addSeparator();
                ToolbarTextItem textPapel = new ToolbarTextItem("Papel: "+sPapel);
                toolbar.addItem(textPapel);
                toolbar.addSeparator();
                Date data = new Date();
                ToolbarTextItem textData = new ToolbarTextItem("Logado: "+data.getHours()+":"+data.getMinutes());
                toolbar.addItem(textData);

                BorderLayoutData southData = new BorderLayoutData(RegionPosition.SOUTH);
                southData.setMinSize(25);
                southData.setMaxSize(100);
                southData.setMargins(new Margins(0, 0, 0, 0));
                southData.setSplit(true);
                borderPanel.add(toolbar, southData);

                final AccordionLayout accordion = new AccordionLayout(true);

                westPanel = new Panel();
                westPanel.setTitle("Menu");
                westPanel.setCollapsible(true);
                westPanel.setWidth(220);
                westPanel.setLayout(accordion);
                BorderLayoutData westData = new BorderLayoutData(RegionPosition.WEST);
                westData.setSplit(true);
                westData.setMinSize(175);
                westData.setMaxSize(400);
                westData.setMargins(new Margins(0, 5, 0, 0));

                Panel navPanelCad = new Panel();
                navPanelCad.setTitle("Ações");
                navPanelCad.setBorder(true);
                navPanelCad.add(criarPanelTreeAcoes());

                Panel navPanelSobre = new Panel();
                navPanelSobre.setTitle("Sobre");
                navPanelSobre.setBorder(true);
                navPanelSobre.add(criarPanelTreeSobre());
                /*btnLogoff = new Button("Logout");
                btnLogoff.setIcon("Images/logOut.png");
                btnLogoff.setTooltip("Clique para efetuar o Log-Off");
                navPanelSobre.addButton(btnLogoff);
                btnLogoff.addListener(new ButtonListenerAdapter() {
                    @Override
                    public void onClick(Button button, EventObject e) {
                        panel.hide();
                        System.gc();
                        criarTelaLogin();
                        new Viewport(loginPanel);
                    }}
                );*/

                westPanel.add(navPanelCad);
                westPanel.add(navPanelSobre);
                borderPanel.add(westPanel, westData);

                centerPanel = new TabPanel();
                centerPanel.setDeferredRender(false);
                centerPanel.setActiveTab(0);
                centerPanel.setAutoShow(true);

                Image img = new Image("Images/logo_227x227.png");
                img.setVisibleRect(-360, -180, 45, 45);

                //MessageBox.alert(Integer.toString(centerPanel.getWidth()));
                centerPanel.add(img);
                borderPanel.add(centerPanel, new BorderLayoutData(RegionPosition.CENTER));
                panel.add(borderPanel);

                new Viewport(panel);
            }
            else {
                MessageBox.alert("Invalido", "Nick e Senha não Conferem!"); }
        }
    }

    private void criarTelaLogin(){
        //criação da tela de login
        loginPanel.setSize(200, 300);
        loginForm = new LoginForm();
        loginForm.setPosition(410, 280);
        loginForm.setSize(365, 130);
        loginPanel.add(loginForm);
        loginForm.show();

        loginForm.loginButton.addListener(new ButtonListenerAdapter() {
            @Override
            public void onClick(Button button, EventObject e) {
               controller.efetuaLogin(
                       loginForm.fName.getText(),
                       loginForm.fpassWord.getText(),
                       new callbackLogin()); }
            }
        );
    }

    @Override
    public void onModuleLoad() {

        criarTelaLogin();

        final AsyncCallback callbackConexao = new AsyncCallback() {
            @Override
            public void onSuccess(Object result) {
               //MessageBox.alert("Conectado com Sucesso!");
            }
            @Override
            public void onFailure(Throwable caught) {
               MessageBox.alert("Error", caught.getMessage());}
        };

        //método chamado para fazer a conexao com o banco de dados no servidor...
        controller.Conexao(odbc, callbackConexao);

         new Viewport(loginPanel);
     }

    private Panel criarPanelTreeAcoes(){
      treePanelCad = new TreePanel();
      treePanelCad.setWidth(200);
      treePanelCad.setHeight(400);
      treePanelCad.setAnimate(true);
      treePanelCad.setEnableDD(true);
      treePanelCad.setContainerScroll(true);
      treePanelCad.setRootVisible(true);
      treePanelCad.setBorder(false);

      treePanelCad.addListener(new TreePanelListenerAdapter(){
            @Override
            public void onClick(TreeNode node, EventObject e){

                int nodeID = Integer.parseInt(node.getId());
                boolean bAchouTab = false;
                Component[] items = centerPanel.getItems();

                //ajuste feito pois o gwt tem um bug no tamanho do panel central...
                if (iTamOriPanel == 0)
                    iTamOriPanel = centerPanel.getHeight();
                centerPanel.setHeight(iTamOriPanel-10);

                switch (nodeID){
                    case 1:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Cadastro de Usuários")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                        if (!bAchouTab){
                            Panel panelUsua = new UsuariosPanel(controller);
                            panelUsua.setTitle("Cadastro de Usuários");
                            panelUsua.setClosable(true);
                            panelUsua.setSize(centerPanel.getWidth(), centerPanel.getHeight());
                            centerPanel.add(panelUsua);
                            centerPanel.activate(panelUsua.getId());
                            toolbar.setHeight(25);
                        }
                        break;

                    case 2:
                        //Component[] itemsProj = centerPanel.getItems();
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Cadastro de Projetos")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                        if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelProj = new ProjetosPanel(controller, sID_Usuario, sPapel);
                            panelProj.setTitle("Cadastro de Projetos");
                            panelProj.setClosable(true);
                            centerPanel.add(panelProj);
                            centerPanel.activate(panelProj.getId());
                        }
                        break;

                    case 3:
                        //Component[] itemsTar = centerPanel.getItems();
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Tarefas")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                        if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelTarefas = new AssumirTarefasPanel(controller, sID_Usuario);
                            panelTarefas.setTitle("Tarefas");
                            panelTarefas.setClosable(true);
                            centerPanel.add(panelTarefas);
                            centerPanel.activate(panelTarefas.getId());
                        }
                        break;

                    case 4:
                        //Component[] itemsDispMat = centerPanel.getItems();
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Disponibilizar Material")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                        if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelDispMaterial = new DisponibilizarMaterialPanel(controller, sID_Usuario);
                            panelDispMaterial.setTitle("Disponibilizar Material");
                            panelDispMaterial.setClosable(true);
                            centerPanel.add(panelDispMaterial);
                            centerPanel.activate(panelDispMaterial.getId());
                        }
                        break;

                    case 5:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Revisar Tarefas")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                        if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelRevTarefas = new RevisarTarefasPanel(controller, sID_Usuario);
                            panelRevTarefas.setTitle("Revisar Tarefas");
                            panelRevTarefas.setClosable(true);
                            centerPanel.add(panelRevTarefas);
                            centerPanel.activate(panelRevTarefas.getId());
                        }
                        break;

                   case 6:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Disponibilizar Unidade")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                        if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelDispOA= new DisponibilizarOAPanel(controller, sID_Usuario);
                            panelDispOA.setTitle("Disponibilizar Unidade");
                            panelDispOA.setClosable(true);
                            centerPanel.add(panelDispOA);
                            centerPanel.activate(panelDispOA.getId());
                        }
                        break;

                   case 7:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Validar Unidades")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                       if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelValidarUnidade = new ValidarUnidadePanel(controller, Integer.parseInt(sID_Usuario));
                            panelValidarUnidade.setTitle("Validar Unidades");
                            panelValidarUnidade.setClosable(true);
                            centerPanel.add(panelValidarUnidade);
                            centerPanel.activate(panelValidarUnidade.getId());
                       }
                       break;

                   case 8:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Verificar Revisões Unidades")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                       if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelVerRev = new VerificarRevisoesPanel(controller, sID_Usuario);
                            panelVerRev.setTitle("Verificar Revisões Unidades");
                            panelVerRev.setClosable(true);
                            centerPanel.add(panelVerRev);
                            centerPanel.activate(panelVerRev.getId());
                       }
                       break;

                  case 9:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Gerar Arquivo SCORM")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                       if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelGerarSCORM = new GerarSCORMPanel(controller, Integer.parseInt(sID_Usuario));
                            panelGerarSCORM.setTitle("Gerar Arquivo SCORM");
                            panelGerarSCORM.setClosable(true);
                            centerPanel.add(panelGerarSCORM);
                            centerPanel.activate(panelGerarSCORM.getId());
                       }
                       break;

                 case 10:
                        for (int i = 0; i < items.length; i++) {
                            Component component = items[i];
                            if (component.getTitle().equals("Baixar Arquivos Projetos")) {
                                centerPanel.activate(component.getId());
                                bAchouTab = true;
                            }
                        }
                       if (!bAchouTab && !sNome.equals("BRANCO")){
                            Panel panelBaixarArqProj = new BaixarArquivosProjetosPanel(controller, sID_Usuario);
                            panelBaixarArqProj.setTitle("Baixar Arquivos Projetos");
                            panelBaixarArqProj.setClosable(true);
                            centerPanel.add(panelBaixarArqProj);
                            centerPanel.activate(panelBaixarArqProj.getId());
                       }
                       break;

                    default: break;
                } } });

            final XMLTreeLoader loader = new XMLTreeLoader(){
                {
                    if (sPapel.equals("Coordenador"))
                      setDataUrl("XML/Cadastros_Coordenador.xml");
                    else if (sPapel.equals("Professor Conteudista"))
                      setDataUrl("XML/Cadastros_Conteudista.xml");
                    else if (sPapel.equals("Designer") || sPapel.equals("Programador"))
                      setDataUrl("XML/Cadastros_Programador.xml");
                    else
                      setDataUrl("XML/Cadastros.xml");
                    setRootTag("menu");
                    setFolderIdMapping("@id");
                    setLeafIdMapping("@id");
                    setFolderTitleMapping("@title");
                    setFolderTag("menuItem");
                    setLeafTitleMapping("@title");
                    setLeafTag("item");
                }
            };

            AsyncTreeNode root = new AsyncTreeNode("Cadastros", loader);
            treePanelCad.setRootNode(root);
            treePanelCad.setRootVisible(false);
            treePanelCad.setUseArrows(true);
            root.expand();
            treePanelCad.expandAll();

            return treePanelCad;
        }

    private Panel criarPanelTreeSobre(){
      treePanelsobre = new TreePanel();
      treePanelsobre.setWidth(200);
      treePanelsobre.setHeight(400);
      treePanelsobre.setAnimate(true);
      treePanelsobre.setEnableDD(true);
      treePanelsobre.setContainerScroll(true);
      treePanelsobre.setRootVisible(true);
      treePanelsobre.setBorder(false);

      treePanelsobre.addListener(new TreePanelListenerAdapter(){
            @Override
            public void onClick(TreeNode node, EventObject e){
                int nodeID = Integer.parseInt(node.getId());
                switch (nodeID){
                    case 1:
                        SobreForm sobre = new SobreForm();
                        sobre.show();
                        break;

                    case 2:
                        panel.hide();
                        System.gc();
                        criarTelaLogin();
                        new Viewport(loginPanel);
                        break;

                    default: break;
                } }
      });

            final XMLTreeLoader loader = new XMLTreeLoader(){
                {
                    setDataUrl("XML/Sobre.xml");
                    setRootTag("menu");
                    setFolderIdMapping("@id");
                    setLeafIdMapping("@id");
                    setFolderTitleMapping("@title");
                    setFolderTag("menuItem");
                    setLeafTitleMapping("@title");
                    setLeafTag("item");
                }
            };

            AsyncTreeNode root = new AsyncTreeNode("Cadastros", loader);
            treePanelsobre.setRootNode(root);
            treePanelsobre.setRootVisible(false);
            treePanelsobre.setUseArrows(true);
            root.expand();
            treePanelsobre.expandAll();

            return treePanelsobre;
        }

    }


